package com.thinkcms.security.custom;

import com.google.common.collect.Sets;
import com.thinkcms.core.utils.Checker;
import com.thinkcms.core.utils.SecurityConstants;
import com.thinkcms.security.properties.PermitAllUrlProperties;
import com.thinkcms.system.api.system.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import java.util.Collection;
import java.util.Set;

/**
 * @ClassName: CustomSecurityMetadataSource
 * @Author: LG 动态的权限验证，根据请求路径判断用户权限是否存在
 * @Date: 2019/4/30 11:38
 * @Version: 1.0
 **/

public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    MenuService menuService;

    @Autowired
    PermitAllUrlProperties permitAllUrlProperties;

    @Value("${spring.application.name}")
    public String application;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String url = ((FilterInvocation) object).getHttpRequest().getServletPath();
        Collection<ConfigAttribute> atts = Sets.newHashSet();
        //查看当前资源是否有权限限制，此处只要认证通过后无需权限也可访问
        boolean ignore=permitAllUrlProperties.ckTheSameApi(application,url);
        if(ignore){
            atts.add(new SecurityConfig(SecurityConstants.NOT_REQUIRED_HAVE_PERM));
            return atts;
        }
        Set<String> perms=menuService.selectPermsByUrl(url);
        if(Checker.BeEmpty(perms)){
            ConfigAttribute configAttribute = new SecurityConfig(SecurityConstants.NOT_REQUIRED_HAVE_PERM);
            atts.add(configAttribute);
        }else{
            perms.stream().forEach(perm->{
                if(Checker.BeNotBlank(perm)){
                    ConfigAttribute configAttribute = new SecurityConfig(perm);
                    atts.add(configAttribute);
                }
            });
        }
        return atts;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
